package com.hdy.oa.web.action.department;

import com.hdy.DBUtils.JDBC;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/dept/modify")
public class DepModifyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String deptNo = request.getParameter("deptNo");
        String dName = request.getParameter("dName");
        String loc=request.getParameter("loc");
        String contextPath= request.getContextPath();

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {
          connection = JDBC.getConnection();
          String sql="update dept set DNAME=?,LOC=? where DEPTNO=?";
          ps=connection.prepareStatement(sql);
          ps.setString(1,dName);
          ps.setString(2,loc);
          ps.setString(3,deptNo);
          count= ps.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
         //重定向
            response.sendRedirect(contextPath+"/dept/list");
        }else {
//            request.getRequestDispatcher("/error.html").forward(request,response);
        // 重定向
            response.sendRedirect(contextPath+"/error.html");
        }

    }
}
